package com.smartstate.admin.biz.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.smartstate.admin.biz.entity.bo.User;
import com.smartstate.admin.biz.entity.vo.PermissionVo;
import com.smartstate.admin.biz.mapper.UserMapper;
import com.smartstate.admin.biz.model.LoginUser;
import com.smartstate.common.base.constants.BizConstants;
import com.smartstate.common.base.exception.CommonException;
import com.smartstate.common.base.httpResult.ResultCode;
import com.smartstate.common.base.httpResult.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Component
@Slf4j
public class SssUserDetailService implements UserDetailsService {
    private static volatile int num=0;
    @Resource
    private UserService userService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("获取用户信息"+num);
        num++;
        if(StringUtils.isBlank(username)){
            throw new CommonException("登录名不能为空");
        }
        User user = userMapper.getById(username);
        if (user == null) {
            throw new CommonException("登录名不存在");
        } else if (BizConstants.USER_STATUS_EXPIRED.equals(user.getStatus())) {
            throw new CommonException("用户已过期");
        } else if (BizConstants.USER_STATUS_LOCKED.equals(user.getStatus())) {
            throw new CommonException("用户已锁定");
        } else if (BizConstants.USER_STATUS_UNUSED.equals(user.getStatus())) {
            throw new CommonException("用户已禁用");
        }
        List<PermissionVo> authList = permissionService.findPermissionByUserId(user.getId());
        List<GrantedAuthority> lists = new ArrayList<>();
        if(authList != null && authList.size()>0){
            for (PermissionVo auth : authList) {
                if (StringUtils.isNotBlank(auth.getCode())) {
                    lists.add(new SimpleGrantedAuthority(auth.getCode()));
                }
            }
        }
        LoginUser loginUser = new LoginUser(user.getUsername(),user.getPassword(),user.getNickname(),user.getStatus(), lists);
        loginUser.setId(user.getId());
        loginUser.setDeptId(user.getDeptId());
        loginUser.setEnterpriseId(user.getEnterpriseId());
        loginUser.setAuthorities(lists);
        return loginUser;
    }
}
